package org.totoro.lock;

import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.env.*;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
 * 代码参考于
 *
 * @author daorc
 * @see RelaxedPropertyResolver#getSubProperties(java.lang.String)
 */
public class OnPropertySourceCondition extends SpringBootCondition {

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

        MultiValueMap<String, Object> allAnnotationAttributes = metadata.getAllAnnotationAttributes(ConditionalOnPropertyPrefix.class.getName());

        if (allAnnotationAttributes != null) {

            List<Object> prefixs = allAnnotationAttributes.get("prefix");

            if (prefixs != null) {
                String prefix = (String) prefixs.get(0);
                Environment environment = context.getEnvironment();
                ConfigurableEnvironment env = (ConfigurableEnvironment) environment;
                MutablePropertySources propertySources = env.getPropertySources();

                for (PropertySource<?> source : propertySources) {
                    if (source instanceof EnumerablePropertySource) {
                        EnumerablePropertySource enumerablePropertySource = (EnumerablePropertySource) source;
                        String[] propertyNames = enumerablePropertySource.getPropertyNames();
                        if (propertyNames != null) {
                            for (String propertyName : propertyNames) {
                                if (propertyName.indexOf(prefix) != -1) {
                                    return ConditionOutcome.match();
                                }

                            }
                        }
                    }
                }
            }
        }

        return ConditionOutcome.noMatch("不匹配");
    }


}
